# -*- coding:utf-8 -*- #
from core.level import InfoData
from core.filters import MonitorFilter, AlarmFilter, LoggerFilter,alarm_list
from core.dispatcher import MonitorDispatcher, AlarmDispatcher, LoggerDispatcher
from utils.alarm import writealarminfo, readalarminfo

class GSys(object):
    """docstring for GSys"""
    def __init__(self, processmanager, config):
        super(GSys, self).__init__()
        '''
        processmanager =<core.processmanager.ProcessManager object at 0xb7b94fcc>
        processmanager 是ProcessManager()的一个实例化对象
        config ={'disk_space': 
                   {'fun': <function get_disk_space at 0xb7b9baac>, 
                   'rate': (1, (30, 60, 120, 180)), 
                   'inet': <core.network.ShortConnection object at 0xb7b94e6c>, 
                   'id': 21, 
                   'param': {'WarningData': 10}
                   }
                   }
                   
        '''
        self.processmanager = processmanager
        self.config = config
        self.threads = []

    def load_config(self, config):
        for t in self.threads:
            self.processmanager.recycle(t)
            self.threads.remove(t)

        self.config = config
        print "self.config===",self.config
        self.start()

    def start(self, Dispatcher, Filter):
        '''
        执行任务分配，数据过滤操作
        
        Dispatcher= <class 'core.dispatcher.MonitorDispatcher'>
        Filter= <class 'core.filters.MonitorFilter'>
        '''
        for k, v in self.config.iteritems():
            '''
            k== disk_space
            v== {'fun': <function get_disk_space at 0xb7b85b54>, 
                 'rate': (1, (30, 60, 120, 180)), 
                 'inet': <core.network.ShortConnection object at 0xb7b80eac>, 
                 'id': 21, 
                 'param': {'WarningData': 10}
                 }
            '''
            dispatcher = Dispatcher(self.config[k]['inet'])
            # t = <CmdThread(Thread-1, initial daemon)>            
            t = self.processmanager.create_thread()
            print 'thread id:', id(t)
            
            # t 是CmdThread的实例对象，调用CmdThread的start方法
            t.start(v['fun'], v['param'], Filter(v['id']),
                    dispatcher, v['rate'][0])
            
            self.threads.append(t)
            



class Monitor(GSys):
    """docstring for Monitor"""
    def __init__(self, processmanager, config):
        #执行父类的初始化,并将processmanager, config 给父类
        super(Monitor, self).__init__(processmanager, config)
        

    def start(self):
        #执行父类的start函数
        super(Monitor, self).start(MonitorDispatcher, MonitorFilter)

        
class Alarm(GSys):
    """docstring for Alarm"""
    def __init__(self, threadmanager, config):
        super(Alarm, self).__init__(threadmanager, config)

    def restore(self):
        #从日志文件中读取预警信息
        # 文件不存在,则第一次为空 alarm_list
        global alarm_list
        print "alarm_list1 ==",alarm_list
        alarm_list.update(readalarminfo())
        print "alarm_list2 ==",alarm_list

    def start(self):
        self.restore()
        super(Alarm , self).start(AlarmDispatcher, AlarmFilter)

    def reset(self):
        """tell server reset all alarm msg"""
        global alarm_list
        try:
            dispatcher = AlarmDispatcher(
                    self.config.popitem()[1]['inet']
                    )
            dispatcher.dispatch(InfoData(
                {'type': 4, 'ids': alarm_list.keys()})
                )
        except KeyError:
            pass
        alarm_list.clear()
        writealarminfo({})

class Logger(GSys):
    """correct unnormal logger"""
    def __init__(self, threadmanager, config):
        super(Logger, self).__init__(threadmanager, config)

    def start(self):
        super(Logger, self).start(LoggerDispatcher, LoggerFilter)
